<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('申请标题')" prop="applyTitle">
            <el-input v-model="form.applyTitle" :placeholder="$t('申请标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="applyUserId">
            <UserSelect v-model="form.applyUserId" :placeholder="$t('申请人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applyTime">
            <el-date-picker
              v-model="form.applyTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('申请时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('外带类型')" prop="takeoutType">
            <el-select v-model="form.takeoutType" :placeholder="$t('请选择')" filterable multiple>
              <el-option
                v-for="dict in takeoutTypeDict"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
                collection-summary-report
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('外出时间')" prop="absenceTime">
            <el-date-picker
              v-model="form.absenceTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('外出时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('预计归还时间')" prop="estimatedTime">
            <el-date-picker
              v-model="form.estimatedTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('预计归还时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('外出地点')" prop="destination">
            <el-input v-model="form.destination" :placeholder="$t('外出地点')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('同行人员')" prop="peersUser">
            <UserSelect v-model="form.peersUser" filterable multiple :placeholder="$t('同行人员')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="postscript">
            <el-input v-model="form.postscript" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
      </el-row>
      <!--文件明细-->
      <div v-if="form.takeoutType.filter(function (item) { return item === 'FILE'; }).length != 0" class="area-header">
        <span class="area-header-title">{{ $t('文件明细') }}</span>
      </div>
      <el-table v-if="form.takeoutType.filter(function (item) { return item === 'FILE'; }).length != 0" :data="form.oaSealOutFileList" border class="nowrapTable formTable">
        <el-table-column :label="$t('文件编号')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('文件编号') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaSealOutFileList.' + scope.$index + '.fileNo'" :rules="oaSealOutFileListRules.fileNo">

              <el-input v-model="scope.row.fileNo" :placeholder="$t('文件编号')" show-word-limit maxlength="100" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('文件类型')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('文件类型') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaSealOutFileList.' + scope.$index + '.fileType'" :rules="oaSealOutFileListRules.fileType">
              <el-input v-model="scope.row.fileType" :placeholder="$t('文件类型')" show-word-limit maxlength="100" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('存放地')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('存放地') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaSealOutFileList.' + scope.$index + '.storingArea'" :rules="oaSealOutFileListRules.storingArea">
              <el-input v-model="scope.row.storingArea" :placeholder="$t('存放地')" show-word-limit maxlength="100" />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column :label="$t('保管人')">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('保管人') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaSealOutFileList.' + scope.$index + '.storageUser'" :rules="oaSealOutFileListRules.storageUser">
              <UserSelect v-model="scope.row.storageUser" filterable :placeholder="$t('保管人')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button v-hasPermi="['oa:sealOut:remove']" size="small" type="text" icon="el-icon-delete" @click="delFileHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide && form.takeoutType.filter(function (item) { return item === 'FILE'; }).length != 0" class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addFileDetails">{{ $t('添加明细') }}</el-button>
      </div>
      <!--章证明细-->
      <div v-if="form.takeoutType.filter(function (item) { return item === 'SEAL'; }).length != 0" class="area-header">
        <span class="area-header-title">{{ $t('章证明细') }}</span>
      </div>
      <el-table v-if="form.takeoutType.filter(function (item) { return item === 'SEAL'; }).length != 0" :data="form.oaSealOutSealList" border class="nowrapTable formTable">
        <el-table-column :label="$t('主体类型')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('主体类型') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaSealOutSealList.' + scope.$index + '.subjectType'" :rules="oaSealOutSealListRules.subjectType">
              <dictSelect
                v-model="scope.row.subjectType"
                :clearable="true"
                dictionary="main_body_type_seal"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('章证主体')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('章证主体') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaSealOutSealList.' + scope.$index + '.subject'" :rules="oaSealOutSealListRules.subject">
              <MainBodySelect
                v-model="scope.row.subject"
                :parameters="scope.row.subjectType"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('印章类型')">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('印章类型') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaSealOutSealList.' + scope.$index + '.sealType'" :rules="oaSealOutSealListRules.sealType">
              <dictSelect
                v-model="scope.row.sealType"
                :clearable="true"
                dictionary="seal_type"
                multiple
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('证照类型')">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('证照类型') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaSealOutSealList.' + scope.$index + '.licenseType'" :rules="oaSealOutSealListRules.licenseType">
              <dictSelect
                v-model="scope.row.licenseType"
                :clearable="true"
                dictionary="license_type"
                multiple
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button v-hasPermi="['oa:sealOut:remove']" size="small" type="text" icon="el-icon-delete" @click="delSealHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide && form.takeoutType.filter(function (item) { return item === 'SEAL'; }).length != 0" class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addSealDetails">{{ $t('添加明细') }}</el-button>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--      保存 取消按钮 oa:sealOut 权限标签-->
      <!--      组件中包含两个按钮-->
      <!--      保存：调用当前页面的 submitForm方法 参数为save-->
      <!--      保存并启动流程:调用当前页面的 submitForm方法 参数为process-->
      <!--      取消：调用当前页面 cancel 方法-->
      <FormBtn ref="formBtn" has-permi="oa:sealOut" :bus-data="form" :btn-hide="btnHide" />
    </div>
  </div>
</template>

<script>
import { saveOaSealOut, getOaSealOut, delOaSealOutFile, delOaSealOutSeal } from '@/api/oa/seal/oaSealOut'
    import MainBodySelect from '@/components/MainBodySelect'
    export default {
      components: {
        MainBodySelect
      },
        data() {
          var checkCertificateSealType = (rule, value, callback) => {
            if (value.length === 0) {
              for (var i = 0; i < this.form.oaSealOutSealList.length; i++) {
                  if (this.form.oaSealOutSealList[i].sealType.length === 0) {
                    if (this.form.oaSealOutSealList[i].licenseType.length === 0) {
                      callback(new Error('至少选择一项章证类型'))
                    }
                  }
              }
            }
            callback()
          }
          var checkCertificateLicenseType = (rule, value, callback) => {
            if (value.length === 0) {
              for (var i = 0; i < this.form.oaSealOutSealList.length; i++) {
                if (this.form.oaSealOutSealList[i].licenseType.length === 0) {
                  if (this.form.oaSealOutSealList[i].sealType.length === 0) {
                    callback(new Error('至少选择一项章证类型'))
                  }
                }
              }
            }
            callback()
          }
          return {
                // 表单参数
                form: {
                  oaSealOutFileList: [],
                  oaSealOutSealList: []
                },
                // 遮罩层
                loading: false,
                // 是否隐藏其它按钮
                otherBtnHide: false,
                // 是否隐藏保存按钮 (流程中需要增加)
                btnHide: false,
                // 外带类型
                takeoutTypeDict: [],
                // 表单校验
                rules: {
                  applyTitle: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
                  applyUserId: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
                  applyTime: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
                  takeoutType: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
                  absenceTime: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
                  estimatedTime: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
                  destination: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }]
                },
                // 校验文件明细不能为空
                oaSealOutFileListRules: {
                  fileNo: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
                  fileType: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
                  storingArea: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
                  storageUser: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }]
                },
                // 校验印章明细不能为空
                oaSealOutSealListRules: {
                  subjectType: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
                  subject: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
                  sealType: [{ required: true, validator: checkCertificateSealType, trigger: ['blur', 'change'] }],
                  licenseType: [{ required: true, validator: checkCertificateLicenseType, trigger: ['blur', 'change'] }]
                }

            }
        },
        created() {
          this.$bus.$emit('async_done')
          this.getDicts('takeout_type').then(response => {
            this.takeoutTypeDict = response.data
          })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    getOaSealOut(data.id).then(response => {
                        this.form = response.data
                        this.loading = false
                    })
                } else {
                    this.reset()
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    applyTitle: undefined,
                    applyUserId: this.$store.state.user.userId,
                    applyTime: new Date(),
                    takeoutType: [],
                    absenceTime: undefined,
                    estimatedTime: undefined,
                    destination: undefined,
                    peersUser: [],
                    postscript: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                    delFlag: undefined,
                    oaSealOutFileList: [],
                    oaSealOutSealList: []
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            // type 保存:save   保存并启动流程:process
            submitForm(type) {
              const file = this.form.oaSealOutFileList
              const seal = this.form.oaSealOutSealList
              // 如果选择了文件外带
              if (this.form.takeoutType.filter(function(item) { return item === 'FILE' }).length !== 0) {
                // 判断文件明细是否为空
                if (file === null || file === [] || file === '' || file <= 0) {
                  this.msgError(this.$t('至少添加一条文件明细'))
                  return false
                }
              }
              // 如果选择了印章外带
              if (this.form.takeoutType.filter(function(item) { return item === 'SEAL' }).length !== 0) {
                // 判断印章明细是否为空
                if (seal === null || seal === [] || seal === '' || seal <= 0) {
                  this.msgError(this.$t('至少添加一条章证明细'))
                  return false
                }
              }
              // 流程需要增加
              return new Promise((resolve, reject) => {
                this.$refs['form'].validate(valid => {
                  // 验证数据
                  if (valid) {
                    this.loading = true
                    // 保存数据
                    saveOaSealOut(this.form).then(response => {
                      if (response.code === 200) {
                        // 点击的按钮是保存并启动流程
                        if (type === 'process') {
                          // 启动流程
                          this.startProcess(response.data)
                        } else {
                          this.msgSuccess(this.$t('保存成功'))
                          // 关闭form页面
                          this.closeForm()
                        }
                        resolve()
                      } else {
                        this.msgError(response.msg)
                        this.loading = false
                        reject()
                      }
                    }).catch(() => {
                      this.loading = false
                    })
                  } else {
                    reject()
                    this.locationError(document)
                  }
                })
              })
           },
          // 启动流程
          startProcess: function(dataId) {
              debugger
            this.loading = false
            // 启动流程时候传入的参数
            const processData = {}
            // 待办标题
            processData.title = this.form.applyTitle
            // 业务表名
            processData.dataTable = 'oa_seal_out'
            // 业务ID 根据 业务表名 和 业务ID 俩个字段来更新流程的审批状态和流程实例ID
            processData.dataId = dataId.id
            // 业务表单地址 待办时查看的页面
            processData.formPath = '@/views/oa/seal/oaSealOutForm'
            // 菜单标识(根据菜单标识判断的走哪个流程)
            processData.menuKey = 'oa_seal_out'
            this.startProcessByMenu(processData, () => {
              this.form.actStatus = 'D'
              this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
              this.closeForm()
            })
          },
          // 文件明细
          addFileDetails() {
            const row = {
              id: undefined,
              fileNo: '',
              fileType: '',
              storingArea: '',
              storageUser: ''
            }
            if (!(this.form.oaSealOutFileList instanceof Array)) {
              this.$set(this.form, 'oaSealOutFileList', [])
            }
            this.$nextTick(() => {
              this.form.oaSealOutFileList.push(row)
            })
          },
          // 印章明细
          addSealDetails() {
            const row = {
              id: undefined,
              subjectType: '',
              subject: '',
              sealType: [],
              licenseType: []
            }
            if (!(this.form.oaSealOutSealList instanceof Array)) {
              this.$set(this.form, 'oaSealOutSealList', [])
            }
            this.$nextTick(() => {
              this.form.oaSealOutSealList.push(row)
            })
          },
          // 删除文件明细
          delFileHandle(index, row) {
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return delOaSealOutFile(id)
                }).then(() => {
                this.form.oaSealOutFileList.splice(index, 1)
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.form.oaSealOutFileList.splice(index, 1)
            }
          },
          // 删除印章明细
          delSealHandle(index, row) {
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return delOaSealOutSeal(id)
                }).then(() => {
                this.form.oaSealOutSealList.splice(index, 1)
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.form.oaSealOutSealList.splice(index, 1)
            }
          }
        }

    }
</script>
